package org.autumn.review.thread;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.sql.Time;
import java.util.concurrent.TimeUnit;

public class FivePersonEat {
    public static void main(String[] args) {
        Chopstick c1 = new Chopstick("1");
        Chopstick c2 = new Chopstick("2");
        Chopstick c3 = new Chopstick("3");
        Chopstick c4 = new Chopstick("4");
        Chopstick c5 = new Chopstick("5");

        new Person("A",c1,c2).start();
        new Person("B",c2,c3).start();
        new Person("C",c3,c4).start();
        new Person("D",c4,c5).start();
        new Person("E",c5,c1).start();
    }
}

@Slf4j
class Person extends Thread{
    Chopstick left;
    Chopstick right;

    public Person(String name, Chopstick left, Chopstick right) {
        super(name);
        this.left = left;
        this.right = right;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (left){
                synchronized (right){
                    try {
                        eat();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    private void eat() throws InterruptedException {
        log.info("{} start eat" ,super.getName());
        TimeUnit.SECONDS.sleep(1);
    }
}

@Data
@AllArgsConstructor
class Chopstick{
    String name;
}